<template>
<div class="giftCardList">
  <search-block type="flex">
    <template slot="button">
      <el-button type="primary" @click="search(true)">查询</el-button>
      <el-button type="primary" @click="batchAddCard">新建批次</el-button>
    </template>
    <el-form inline :model="model" @submit.native.prevent>
      <el-form-item label="卡批次:">
        <el-input v-model="model.batchCode" clearable></el-input>
      </el-form-item>
      <el-form-item label="卡名称:">
        <el-input v-model="model.batchName" clearable></el-input>
      </el-form-item>
    </el-form>
  </search-block>
  <y-table
    ref="table"
    border
    pagination
    :getDataWay="getDataWay"
    :columns="columns"
  >
    <el-table-column slot="y-oper" label="操作" align="center" header-align="center" width="200" fixed="right">
      <template v-slot="{row}">
        <div class="wrap-table-buttons">
          <el-button size="mini" @click="batchViewCard(row)">批次详情</el-button>
          <el-button type="primary" size="mini" @click="addCard(row)">发行礼金卡</el-button>
          <el-button size="mini" @click="showDetailList(row)">发行列表</el-button>
          <el-button size="mini" @click="batchExpert(row)">导出礼金卡</el-button>
        </div>
      </template>
    </el-table-column>
  </y-table>
  <y-form
    ref="yForm"
    v-model="batchForms.formModel"
    :visible.sync="batchForms.showForm"
    :show-button="batchForms.formsType !== 'VIEW'"
    :title="batchForms.formTypeTitle[batchForms.formsType]"
    destroy-on-close
    width="900px"
    :form-attrs="batchFormAttrs"
    :columns="batchFormColumns"
    @ensure="batchEnsureModel">
  </y-form>
  <y-form
    v-if="forms.currentForm"
    ref="yForm"
    v-model="forms.formModel"
    :visible.sync="forms.showForm"
    :title="`发行礼金卡【${forms.currentForm.batchName}】`"
    destroy-on-close
    width="400px"
    :form-attrs="forms.formAttrs"
    :columns="formColumns"
    @ensure="ensureModel">
    <span slot="y-form-tip" class="gift-card-tip y-success">{{`剩余可发行量：${forms.currentForm.total - (forms.currentForm.totaled || 0)}张`}}</span>
  </y-form>
  <el-dialog
    v-if="detailForms.batchId && detailForms.batchName"
    :visible.sync="detailForms.showForm"
    :title="`【${detailForms.batchName}】发行详情`"
    class="force-inner-scroll"
    width="1100px"
    @closed="resetDetailForm">
    <gift-card-item-list v-if="detailForms.batchId" :batch-id="detailForms.batchId"></gift-card-item-list>
  </el-dialog>
</div>
</template>

<script>
import GiftCardItemList from "@/views/sem/giftCardItemList";
export default {
  name: "giftCardList",
  components: {GiftCardItemList},
  inject: ['getEnum'],
  computed:{
    getDataWay(){
      return{
        dataType: 'url',
        data: this.$api.sem.giftCardBatchPage,
        param: this.model
      }
    },
    batchFormColumns(){
      return[
        {
          label: "礼金卡批次名称",
          prop: "batchName",
          comp:{
            compType: 'input',
            attrs:{
              maxlength: 30,
              showWordLimit: true
            }
          }
        },
        {
          label: "可发行量(张)",
          prop: "total",
          comp:{
            compType: 'input-number',
            attrs:{
              stepStrictly: true,
              controls: false,
              min: 1
            }
          }
        },
        {
          label: "面额(元)",
          prop: "couponValue",
          comp:{
            compType: 'input-number',
            attrs:{
              stepStrictly: true,
              controls: false,
              min: 1
            }
          }
        },
        {
          label: "有效截止日期",
          prop: "deadLine",
          comp:{
            compType: 'datePicker',
            attrs: {
              type: "date",
              pickerOptions:{
                disabledDate(time) {
                  return time.getTime() < Date.now();
                },
                shortcuts: [{
                  text: '今天',
                  onClick(picker) {
                    picker.$emit('pick', new Date());
                  }
                }]
              },
              valueFormat: 'yyyy-MM-dd'
            }
          }
        },
        {
          label: "备注",
          prop: "remarks",
          comp:{
            compType: 'input',
            attrs:{
              type: 'textarea',
              maxlength: 100,
              showWordLimit: true,
              autosize: {
                minRows: 3
              }
            }
          }
        }
      ]
    },
    batchFormAttrs(){
      return{
        labelWidth: '140px',
        disabled: this.batchForms.formsType === 'VIEW',
        rules: {
          batchName: [{required: true, message: "请输入卡批次名称", trigger: "blur"}],
          deadLine: [{required: true, message: "请选择有效期", trigger: "change"}],
        }
      }
    },
    formColumns(){
      return [
        {
          label: "发行量(张)",
          prop: "num",
          comp:{
            compType: 'input-number',
            attrs:{
              stepStrictly: true,
              controls: false,
              min: 1,
              max: this.forms.currentForm? (this.forms.currentForm.total - (this.forms.currentForm.totaled || 0)) : 0
            }
          }
        }
      ]
    }
  },
  data(){
    return{
      model:{
        batchCode: '',
        batchName: ''
      },
      columns: [
        {
          label: '卡批次',
          prop: 'batchCode',
          minWidth: 155
        },
        {
          label: '卡名称',
          prop: 'batchName',
          minWidth: 155
        },
        {
          label: '已发行/可发行总量',
          prop: 'total',
          minWidth: 155,
          formatter(row){
            return `${row.totaled || 0}张/${row.total}张`
          }
        },
        {
          label: '金额',
          prop: 'couponValue',
          minWidth: 155,
          formatter({couponValue}){
            return '￥' + couponValue;
          }
        },
        {
          label: '到期时间',
          prop: 'deadLine',
          minWidth: 170
        }
      ],
      forms:{
        formModel:{
          num: ''
        },
        showForm: false,
        currentForm: null,
        formAttrs:{
          labelWidth: '120px'
        }
      },
      batchForms:{
        formsType: '',
        formTypeTitle: {
          'ADD': '新建批次',
          'EDIT': '编辑批次',
          'VIEW': '批次详情'
        },
        formModel:{
          batchName: '',
          remarks: '',
          couponValue: '',
          deadLine: '',
          total: ''
        },
        currentForm: null,
        showForm: false,
      },
      detailForms:{
        showForm: false,
        batchId: '',
        batchName: '',
      }
    }
  },
  methods:{
    search(jumpToFirst){
      this.$refs['table'].loadData(this.model, jumpToFirst);
    },
    resetForm(){
      Object.keys(this.forms.formModel).map(key => {
        this.forms.formModel[key] = '';
      })
    },
    addCard(row){
      this.forms.currentForm = row;
      this.resetForm();
      this.forms.showForm = true;
    },
    delCard(row){
      this.$yAxios({
        url: this.$api.sem.removeGiftCard,
        data:{
          ids: [row.id]
        }
      }, info => {
        this.$message({
          type: 'success',
          message: '删除成功'
        });
        this.search();
      })
    },
    ensureModel(form){
      let newForm = Object.assign({
        batchId: this.forms.currentForm.id
      }, form);
      this.$yAxios({
        url: this.$api.sem.saveGiftCard,
        data: newForm
      }, info => {
        this.$message({
          type: 'success',
          message: '保存成功'
        });
        this.search();
      })
    },
    batchResetForm(){
      Object.keys(this.batchForms.formModel).map(key => {
        this.batchForms.formModel[key] = this.batchForms.currentForm ? this.batchForms.currentForm[key] : '';
      })
    },
    batchAddCard(){
      this.batchForms.formsType = 'ADD';
      this.batchForms.currentForm = null;
      this.batchResetForm();
      this.batchForms.showForm = true;
    },
    batchViewCard(row){
      this.batchForms.formsType = 'VIEW';
      this.batchForms.currentForm = row;
      this.batchResetForm();
      this.batchForms.showForm = true;
    },
    batchEnsureModel(form){
      let newForm;
      if(this.forms.formsType === 'EDIT'){
        newForm = Object.assign({}, this.forms.currentForm, form);
      }else{
        newForm = form;
      }
      this.$yAxios({
        url: this.$api.sem.saveGiftCardBatch,
        data: newForm
      }, info => {
        this.$message({
          type: 'success',
          message: '保存成功'
        });
        this.search(this.forms.formsType === 'ADD');
      })
    },
    batchExpert(row){
      this.$yAxios({
        url: this.$api.sem.exportGiftCardBatch,
        data:{
          id: row.id
        },
        loading: true
      }, info => {
        if(info?.length){
          let data = [
            ['卡号', '卡密']
          ];
          data.push(...info.map(item => [item.couponItemSn, item.secret]));
          this.$$exportExcel({
            data, fileName: row.batchName + '.xlsx'
          })
        }else{
          this.$message({
            type: 'warning',
            message: '该批次不存在已发行的卡'
          });
        }
      })
    },
    resetDetailForm(){
      this.detailForms.batchId = '';
      this.detailForms.batchName = '';
    },
    showDetailList(row){
      this.detailForms.batchId = row.id;
      this.detailForms.batchName = row.batchName;
      this.detailForms.showForm = true;
    }
  }
}
</script>

<style scoped lang="less">
.giftCardList{
  .gift-card-tip{
    display: block;
    margin: -20px 0 10px;
    text-align: center;
  }
}
</style>